package com.yaolaizaixian.merchant.order;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.yaolaizaixian.merchant.R;
import com.yaolaizaixian.merchant.base.BaseActivity;
import com.yaolaizaixian.merchant.base.BaseInfo;
import com.yaolaizaixian.merchant.base.BaseModel;
import com.yaolaizaixian.merchant.bean.Customer;
import com.yaolaizaixian.merchant.bean.MemberInfo;
import com.yaolaizaixian.merchant.bean.MemberInfoModel;
import com.yaolaizaixian.merchant.home.SaoMaActivity;
import com.yaolaizaixian.merchant.utils.AppManager;
import com.yaolaizaixian.merchant.utils.GsonUtil;
import com.yaolaizaixian.merchant.utils.LogUtil;
import com.yaolaizaixian.merchant.utils.MyNetUtils;
import com.yaolaizaixian.merchant.utils.SharedPreferencesUtil;
import com.yaolaizaixian.merchant.utils.Toasty;
import com.zhy.autolayout.AutoLinearLayout;
import com.zhy.autolayout.AutoRelativeLayout;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

/**
 * Created by ylzx on 2017/2/23.
 * <p/>
 * 耀莱会员信息查询
 */
public class InformationServiceActivity extends BaseActivity {

    @BindView(R.id.ll_back)
    AutoLinearLayout llBack;
    @BindView(R.id.tv_title_text)
    TextView tvTitleText;
    @BindView(R.id.ll_chathome_saoyissao)
    LinearLayout llChathomeSaoyissao;
    @BindView(R.id.ll_chathome_seach)
    LinearLayout llChathomeSeach;
    @BindView(R.id.tv_head)
    ImageView tvHead;
    @BindView(R.id.tv_shopname)
    TextView tvShopname;
    @BindView(R.id.tv_username)
    TextView tvUsername;
    @BindView(R.id.iv_query)
    ImageView ivQuery;
    @BindView(R.id.et_login_num)
    EditText etLoginNum;
    @BindView(R.id.ll_etquery)
    AutoLinearLayout llEtquery;
    @BindView(R.id.rl_query)
    AutoRelativeLayout rlQuery;
    @BindView(R.id.ll_order_info)
    AutoLinearLayout llOrderInfo;
    private String TAG = "InformationServiceActivity";

    //判断去往何方
    private String type;
    //是否正在
    private boolean ischeck = true;
    private Handler mhandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {

            switch (msg.what) {

                case 1:

                    String result = (String) msg.obj;

                    LogUtil.LogShitou(TAG, result);

                    BaseModel baseModel = GsonUtil.jsonToBean(result, BaseModel.class);

                    if (baseModel.isFlag()) {

                        MemberInfoModel memberInfoModel = GsonUtil.jsonToBean(result, MemberInfoModel.class);

                        MemberInfo memberInfo = memberInfoModel.getData();

                        Customer customer = memberInfo.getCustomer();

                        if (null != customer) {

                            if (!TextUtils.isEmpty(type) && type.equals("1")) {

                                ischeck = true;
                                Intent intent = new Intent(InformationServiceActivity.this, QueryResultActivity.class);
                                intent.putExtra("phone", etLoginNum.getText().toString().trim());
                                //1手机号 2卡号
                                startActivity(intent);
                                ischeck = true;

                            }
                        }

                    } else {

                        ischeck = true;
                        //如果是账号被停用，就踢出到登录页面
                        if (baseModel.getErrorCode().equals(BaseInfo.LogOutCode)) {

                            showConflictDialog(InformationServiceActivity.this, "账号被停用");

                        } else if (baseModel.getErrorCode().equals(BaseInfo.LogOutCode1)) {

                            showConflictDialog(InformationServiceActivity.this, "您的账号在其它设备登录");

                        } else {

                            Toasty.error(getApplicationContext(), baseModel.getErrorMsg(), Toast.LENGTH_SHORT).show();

                            return;
                        }
                    }
                    break;
            }
        }
    };


    @Override
    public void initView() {

        setContentView(R.layout.activity_order_information);
    }

    @Override
    public void initData() {

        //用户名称
        String username = SharedPreferencesUtil.getString(getApplicationContext(), "username", "");
        String Shopname = SharedPreferencesUtil.getString(getApplicationContext(), "Shopname", "");
        String menname = SharedPreferencesUtil.getString(getApplicationContext(), "menname", "");
        tvShopname.setText("【" + Shopname + "】");
        if (!TextUtils.isEmpty(menname)) {
            tvUsername.setText(username + "(" + menname + ")");
        } else {
            tvUsername.setText(username);
        }
        llChathomeSeach.setVisibility(View.GONE);
        type = getIntent().getStringExtra("type");
        if (!TextUtils.isEmpty(type)) {

            if ("1".equals(type)) {

                tvTitleText.setText("会员权益查询");

            } else {

                tvTitleText.setText("订单核销");
            }
        }
        String logoimage = SharedPreferencesUtil.getString(InformationServiceActivity.this, "shopImage", "");
        Log.e(TAG, "logoimage==" + logoimage);
        Glide
                .with(InformationServiceActivity.this)
                .load(logoimage)
                .placeholder(R.mipmap.noload)
                .error(R.mipmap.noload)
                .into(tvHead);
        llOrderInfo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hind();
            }
        });

        etLoginNum.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    // 此处为得到焦点时的处理内容
                    llEtquery.setBackground(getResources().getDrawable(R.drawable.bg_edittext_focused));
                    ivQuery.setImageResource(R.mipmap.user_input);
                } else {
                    // 此处为失去焦点时的处理内容
                    llEtquery.setBackground(getResources().getDrawable(R.drawable.eidttextshape));
                    ivQuery.setImageResource(R.mipmap.user_icon);
                }
            }
        });

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();

        AppManager.getAppManager().finishActivity(this);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
        AppManager.getAppManager().addActivity(this);
    }

    @OnClick({R.id.ll_back, R.id.rl_query, R.id.ll_chathome_saoyissao})
    public void onClick(View view) {
        switch (view.getId()) {

            case R.id.ll_back:

                finish();

                break;

            case R.id.rl_query:

                if (ischeck) {

                    ischeck = false;

                    if (TextUtils.isEmpty(etLoginNum.getText().toString().trim())) {

                        Toasty.error(getApplicationContext(), "请输入会员卡号或手机号", Toast.LENGTH_SHORT, true).show();
                        ischeck = true;

                        return;

                    }
//                else if (!isMobileNO(etLoginNum.getText().toString().trim())){
//
//                    Toasty.error(getApplicationContext(), "请输入正确的手机号", Toast.LENGTH_SHORT, true).show();
//                    ischeck=true;
//                    return;
//                }
                    else {

                        checkCustomer();
                    }

                }
                break;

            //进入扫码界面
            case R.id.ll_chathome_saoyissao:

                if (Build.VERSION.SDK_INT >= 23) {
                    PackageManager packageManager = getPackageManager();
                    int permission = packageManager.checkPermission("android.permission.CAMERA", this.getPackageName());
                    if (PackageManager.PERMISSION_GRANTED == permission) {

                        Intent intent = new Intent(InformationServiceActivity.this, SaoMaActivity.class);
                        intent.putExtra("type", type);
                        //标记是查询订单还是个人信息
                        intent.putExtra("sign", "1");
                        startActivity(intent);

                    } else {
                        //没有这个权限
                        Toasty.error(getApplicationContext(), "请在应用设置界面打开本应用照相机权限", Toast.LENGTH_SHORT).show();
                    }
                } else {

                    if (cameraIsCanUse()) {
                        Intent intent = new Intent(InformationServiceActivity.this, SaoMaActivity.class);
                        intent.putExtra("type", type);
                        //标记是查询订单还是个人信息
                        intent.putExtra("sign", "1");
                        startActivity(intent);
                        //有这个权限
                    } else {
                        Toasty.error(getApplicationContext(), "请在应用设置界面打开本应用照相机权限", Toast.LENGTH_SHORT).show();
                    }

                }

                break;
        }
    }

    //6.0以下系统判断照相机权限
    public boolean cameraIsCanUse() {
        boolean isCanUse = true;
        Camera mCamera = null;
        try {
            mCamera = Camera.open();
            Camera.Parameters mParameters = mCamera.getParameters(); //针对魅族手机
            mCamera.setParameters(mParameters);
        } catch (Exception e) {
            isCanUse = false;
        }

        if (mCamera != null) {
            try {
                mCamera.release();
            } catch (Exception e) {
                e.printStackTrace();
                return isCanUse;
            }
        }
        return isCanUse;
    }

    //检查会员信息
    private void checkCustomer() {

        String shopsysno = SharedPreferencesUtil.getString(getApplicationContext(), "shopsysno", "");
        //店铺id
        final String url = BaseInfo.URL + "customerInfo/info.do";
        HashMap<String, String> sortedParams = new HashMap<String, String>();
        // sysNo 值  3des加密
        sortedParams.put("cardNumber", etLoginNum.getText().toString().trim());
        sortedParams.put("shopStoreSysno", shopsysno);
        //类型，1：手机号，2：卡号
        // sortedParams.put("cardType", "1");
        //判断是抵扣 还是抵用
        if (!TextUtils.isEmpty(type) && type.equals("1")) {
            //权益类型：1抵扣 2抵用
            sortedParams.put("equityRuleType", "2");

        } else {

            //1抵扣 2抵用
            sortedParams.put("equityRuleType", "1");
        }

        OkHttpUtils
                .post()
                .url(url)
                .params((HashMap) MyNetUtils.getInstance().getNetData(sortedParams, getApplicationContext()))
                .build()
                .execute(new MyStringCallback());

    }


    class MyStringCallback extends StringCallback {
        @Override
        public void onError(Call call, Exception e, int id) {

            ischeck = true;
            Toasty.error(getApplicationContext(), "网络异常", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onResponse(String response, int id) {

            Message message = new Message();
            message.what = 1;
            message.obj = response;
            mhandler.sendMessage(message);
        }
    }

    public boolean isMobileNO(String mobiles) {
        Pattern p = Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[0-9]))\\d{8}$");
        Matcher m = p.matcher(mobiles);
        return m.matches();
    }

    public void hind() {

        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm.isActive() && getCurrentFocus() != null) {
            if (getCurrentFocus().getWindowToken() != null) {

                imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
    }


}
